<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="考试成绩" prop="examScore">
          <el-input v-model="queryParams.examScore" placeholder="请输入考试成绩" clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:studentgrade:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:studentgrade:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:studentgrade:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['system:enroll:import']"
          >导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:studentgrade:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" />
        <el-table-column label="学号"  align="center" prop="studentSno" />
        <el-table-column label="学生姓名"  align="center" prop="studentName" />
        <el-table-column label="学期"  align="center" prop="termName" width="200" />
        <el-table-column label="课程"  align="center" prop="courseName" />
        <el-table-column label="考试成绩"  align="center" prop="examScore" />
        <el-table-column label="补考成绩"  align="center" prop="muExamScore"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:studentgrade:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:studentgrade:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination  v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 添加或修改定时成绩对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="学号" prop="studentSno">
                <el-input v-model="form.studentSno" placeholder="请输入学号" type="number" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学期" prop="termId">
                <el-select v-model="form.termId" placeholder="请选择学期" clearable>
                  <el-option
                    v-for="item in termList"
                    :key="item.id"
                    :label="item.termName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="课程" prop="courseId">
                <el-select v-model="form.courseId" placeholder="请选择课程" clearable>
                  <el-option
                    v-for="item in courseList"
                    :key="item.courseId"
                    :label="item.courseName"
                    :value="item.courseId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考试成绩" prop="examScore">
                <el-input v-model="form.examScore" placeholder="请输入考试成绩" type="number" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="补考成绩">
                <el-input v-model="form.muExamScore" placeholder="请输入补考成绩" type="number" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listScore, getScore, addScore, updateScore, delScore, getStudentCourses} from "@/api/teachMan/score";
  import { courseList,termList } from "@/api/student";
  import { getToken } from "@/utils/auth";
  export default {
    name: "Score",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 定时成绩表格数据
        dataList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          examScore: null,
          studentName: null,
        },
        // 表单参数
        form: {
          studentSno:null,
          termId:null,
          examScore:null,
          muExamScore:null,
        },
        // 表单校验
        rules: {
          studentSno: [
            { required: true, message: "必填且只能输入数字", trigger: "blur" },
          ],
          termId: [
            { required: true, message: "必填", trigger: "blur" },
          ],
          courseId: [
            { required: true, message: "必填", trigger: "blur" },
          ],
          examScore: [
            { required: true, message: "必填且只能输入数字", trigger: "blur" },
          ],
        },
        courseList:[],
        termList:[],
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/studentgrade/import"
        },
      };
    },
    watch: {
    // 2. 同时监听学号和学期
    'form.studentSno'() {
      this.loadCourseList()
    },
    'form.termId'() {
      this.loadCourseList()
    }
  },
    created() {
      this.getList();
       // 获取课程下拉接口
    },
    methods: {
      /** 查询定时成绩列表 */
      getList() {
        this.loading = true;
        listScore(this.queryParams).then(response => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          studentSno:null,
          termId:null,
          examScore:null,
          muExamScore:null,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.gradeId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      // 下拉获取学期数据
      getSelectList(){
        termList().then(res=>{
          this.termList = res
        })
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getSelectList()
        this.open = true;
        this.title = "添加成绩";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.gradeId || this.ids;
        getScore(id).then(async response => {
          this.form = response.data;
          await this.getSelectList()
          await this.loadCourseList(this.form.courseId)
          this.open = true;
          this.title = "修改成绩";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this. queryParams={
          pageNum: 1,
          pageSize: 10,
          examScore: null,
          studentName: null,
        },
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.gradeId != undefined) {
              this.form.id = this.form.gradeId
              updateScore(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addScore(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.gradeId || this.ids;
        this.$modal.confirm('是否确认删除？').then(function() {
          return delScore(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/studentgrade/export', {
          ...this.queryParams
        }, `成绩${new Date().getTime()}.xlsx`)
      },
       /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "学生成绩导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('system/studentgrade/import/template', {}, `学生成绩表${new Date().getTime()}.xlsx`)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList){
        console.log('处理',response, file, fileList)
        this.upload.isUploading = true;
      },
      handleFileSuccess(response, file, fileList){
        console.log('成功',response, file, fileList)
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if(response.code == 500){
          this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "<div style='color: red;'>" +'错误信息：' + response.data[0] + '<div>' + "</div>", "导入结果", { dangerouslyUseHTMLString: true },
          );
          
        }else{
          this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true }); 
        }
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      // 3. 加载课程下拉列表
      async loadCourseList(a) {
        const { studentSno, termId } = this.form
        if (studentSno && termId) {
          let data = {
            studentSno: studentSno, 
            termId: termId
          }
          try {
            const res = await getStudentCourses(data)
            this.courseList = res.data || []
            this.form.courseId = !!a ? a :''   // 清空旧值
          } catch (error) {
            console.error('获取课程列表失败:', error)
            this.courseList = []
            this.form.courseId = ''
          }
        } else {
          this.courseList = []
          this.form.courseId = ''
        }
      }
    }
  };
</script>

<style>
  .el-input--medium .el-input__inner{
    width: 260px;
  }
</style>